package com.code2roc.jarmanage.servlet.nginx;

import com.code2roc.jarmanage.db.ConfigDB;
import com.code2roc.jarmanage.depoly.DepolyPlatform;
import com.code2roc.jarmanage.model.ConfigDO;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class NginxConfigUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap paramMap = CommonUtil.getParamMap(req);
        String fileContent = ConvertUtil.convert2String(paramMap.get("fileContent"));
        ConfigDO configDO = ConfigDB.selectOne("NGINX_HOME");
        String filePath = configDO.getConfigValue() + File.separator + "conf" + File.separator + "nginx.conf";
        FileUtil.writeFile(filePath, fileContent, false);
        String reloadService = ConvertUtil.convert2String(paramMap.get("reloadService"));
        if (reloadService.equals("1")) {
            String platform = EnviromentUtil.getDepolyPlaform();
            if (platform.equals(DepolyPlatform.Windows)) {
                String reloadCommand = "taskkill /f /t /im nginx.exe & start nginx";
                CMDUtil.executeWindowCommand(reloadCommand, configDO.getConfigValue());
            } else {
                String reloadCommand = "cd "+configDO.getConfigValue()+"/sbin/;./nginx -s reload";
                CMDUtil.executeLinuxCommand(reloadCommand);
            }
        }
        resp.getWriter().println(result.toString());
    }
}
